"""
Copyright (c) 2023 - present SKbioinfo
"""

from flask_restful import reqparse,Resource
from flask import request,jsonify
from flask_login import login_required,current_user

from apps.NGS_API.record.interface_operate_his import parse_reason
from apps.NGS_API.utils.log_helper import lg
from apps.NGS_API.extraction.db_extraction import *
from apps.NGS_API.connector.db_common import *
from apps.NGS_API.common.db_table_config import *
from apps.NGS_API.record.history_util import *
pm = operation_monitor(table_name=ngs_op_log["name"])

'''
    Extraction infos.NGS_API
'''
class interfaceExtraction(Resource):
    @login_required
    def get(self):
        try:
            extraction = {}
            ### receive extraction base infos from database ###
            extraction_base_info = get_extraction_info()
            ### collect extraction base info ###
            extraction_infos=[]
            for ext in extraction_base_info:
                extraction_infos.append({
                    "id": ext[0],
                    "ext_id": ext[1],
                    "stc_id": ext[2],
                    "sam_id": ext[3],
                    "op_user": ext[4],
                    "ch_user": ext[5],
                    "op_time": ext[6],
                    "cre_time": ext[7],
                    "md_time": ext[8],
                    "proj_id": ext[9],
                    "flag": False
                })
            extraction["extraction_infos"] = extraction_infos
            response=jsonify(extraction)
            response.status=202
            return response
        except Exception as e:
            lg.error(e)

class interfaceExtractionID(Resource):
    @login_required
    def delete(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                ### SQL: record reason details ###
                reason_details = parse_reason(data=request.json)
                ### SQL: record user operation ###
                record_user_operate(
                    pm = pm,
                    current_user = current_user,
                    record_table = ngs_op_log["name"],
                    resource_table = extraction_db["name"],
                    ch_user = current_user,
                    type_name = "delete",
                    cols = '''
                        extraction_id
                    ''',
                    id = id,
                    reason_details = reason_details
                )
                ### SQL: query outstock sample id ###
                query_sql = '''
                    SELECT 
                        {col} 
                    FROM 
                        {table_name}
                '''.format(
                    col = extraction_qc_db["match"]["ext_id"].split("|")[0],
                    table_name =  extraction_qc_db["name"]
                )
                tmp_result = query_info(query_sql)
                if len(tmp_result) == 0 or tmp_result == None:
                    print("extraction qc table is empty!")
                else:
                    delete_id = tmp_result[0][0]
                    ### SQL: delete stock infos ###
                    qc_delete_sql = '''DELETE FROM {table_name} WHERE {db_name} = \"{col_value}\"'''.format(
                        table_name =  extraction_qc_db["name"],
                        db_name = extraction_qc_db["match"]["ext_id"].split("|")[0],
                        col_value = delete_id
                    )
                    ### STEP 1: delete extraction qc infos ###
                    delete_info(qc_delete_sql)
                ### SQL: delete extraction infos ###
                delete_sql = "DELETE FROM {table_name} WHERE {db_name} = \"{col_value}\"".format(
                    table_name=extraction_db["name"],
                    col_value=id,
                    db_name="id"
                )
                ### STEP 2: delete extraction infos ###
                delete_info(delete_sql=delete_sql)
                return id
        except Exception as e:
            lg.error(e)
    @login_required        
    def post(self,id):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument("reason",type=str,help="",required=True)
            parser.add_argument("extra",type=str,help="",required=True)
            args=parser.parse_args()
            ### SQL: record reason details ###
            reason_details = parse_reason(data=args)
            ### SQL: record user operation ###
            record_user_operate(
                pm = pm,
                current_user = current_user,
                record_table = ngs_op_log["name"],
                resource_table = extraction_db["name"],
                ch_user = current_user,
                type_name = "delete",
                cols = '''
                    extraction_id
                ''',
                id = id,
                reason_details = reason_details
            )
            ### SQL: query outstock sample id ###
            query_sql = '''
                SELECT 
                    {col} 
                FROM 
                    {table_name}
            '''.format(
                col = extraction_qc_db["match"]["ext_id"].split("|")[0],
                table_name =  extraction_qc_db["name"]
            )
            tmp_result = query_info(query_sql)
            if len(tmp_result) == 0 or tmp_result == None:
                print("the extraction qc table is empty!")
            else:
                delete_id = tmp_result[0][0]
                ### SQL: delete stock infos ###
                qc_delete_sql = '''DELETE FROM {table_name} WHERE {db_name} = \"{col_value}\"'''.format(
                    table_name =  extraction_qc_db["name"],
                    db_name = extraction_qc_db["match"]["ext_id"].split("|")[0],
                    col_value = delete_id
                )
                ### STEP 1: delete extraction qc infos ###
                delete_info(qc_delete_sql)
            ### SQL: Delete infos from extraction table ###
            extraction_delete_sql = "DELETE FROM {table_name} WHERE {col_name} =\"{col_value}\"".format(
                table_name = extraction_db["name"],
                col_value = id,
                col_name = "id"
            )
            ### STEP 2: delete extraction infos ###
            delete_info(delete_sql=extraction_delete_sql)
        except Exception as e:
            lg.error(e)
    @login_required          
    def put(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                parser = reqparse.RequestParser()
                parser.add_argument('id',type=str,required=True,help="ID输入有误")
                parser.add_argument('proj_id',type=str,required=True,help="项目ID输入错误")
                parser.add_argument('ext_id',required=True,type=str,help='抽提ID验证错误') 
                parser.add_argument('stc_id',type=str, required=True,help='存货ID验证错误')
                parser.add_argument('sam_id',type=str,required=True,help="样品ID验证错误")
                parser.add_argument('op_user', type=str, required=True,help="质检员ID错误")
                parser.add_argument('ch_user', type=str,required=True,help="审核人ID有误")
                parser.add_argument('op_time', type=str,required=True,help="操作时间有误")
                parser.add_argument('cre_time', type=str,required=True,help="创建时间不能为空")
                args=parser.parse_args(strict=True)
                ### SQL: record update operation ###
                record_user_operate(
                        pm = pm,
                        tag = "ext_id",
                        current_user = current_user,
                        record_table = ngs_op_log["name"],
                        resource_table = extraction_db["name"],
                        ch_user = current_user,
                        type_name = "put",
                        cols = extraction_db["match"],       
                        id = id,
                        later_infos = args,
                        reason_details = ""
                )
                ### SQL: update extraction infos ###
                extraction_update_sql="""
                UPDATE {table_name} SET 
                    extraction_id=\"{extraction_id}\",
                    stock_id=\"{stock_id}\",
                    sample_id=\"{sample_id}\",
                    operate_user=\"{op_user}\",
                    check_user=\"{ch_user}\",
                    # operate_time=\"{op_time}\",
                    # create_time=\"{cre_time}\",
                    modify_time=\"{md_time}\"         
                WHERE id=\"{id}\"
                """.format(
                        table_name = extraction_db["name"],
                        extraction_id=args.get("ext_id"),
                        stock_id=args.get("stc_id"),
                        sample_id=args.get("sam_id"),
                        op_user=args.get("op_user"),
                        ch_user=args.get("ch_user"),
                        op_time=args.get("op_time"),
                        cre_time=args.get("cre_time"),
                        md_time=get_current_time(),
                        id=args.get("id")
                )
                update_info(update_sql=extraction_update_sql)
            return id
        except Exception as e:
            lg.error(e)
